<template>
  <div class="user-manager">
    <div class="query-form">
      <el-form :inline="true" :model="roleForm" class="demo-form-inline">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit()">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="roleCreate">创建</el-button>
      </div>
      <el-table ref="multipleTableRef" :data="roleList" style="width: 100%">
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
        >
        </el-table-column>

        <el-table-column label="操作" min-width="250">
          <template #default="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="openPremission(scope.row)"
              >设置权限</el-button
            >
            <el-button type="danger" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="showMadol" title="角色新增">
      <el-form :model="roleForm" ref="dialogForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="roleForm.remark" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 权限窗口 -->
    <el-dialog v-model="premissionModal" title="权限设置">
      <el-form label-width="100px">
        <el-form-item label="角色名称">
          {{ roleName }}
        </el-form-item>
        <el-form-item label="权限设置">
          <el-tree
            ref="tree"
            :data="menuList"
            show-checkbox
            :props="{ label: 'menuName' }"
            node-key="_id"
            default-expand-all
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button>取消</el-button>
          <el-button type="primary" @click="premissionSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<!-- 
  制作权限分配的流程：
  step1 制作对应的弹窗并且把菜单渲染到弹窗中
 -->
<script setup>
import api from "../api/index";
import { ref, reactive, toRaw, nextTick } from "vue";
import utils from "../utils/utils";

// 定义选中的角色id
const roleId = ref("");
// 定义显示的roleName
const roleName = ref("");
// 定义权限弹窗变量
const premissionModal = ref(false);
// 定义
const premissionList = ref([]);
// 定义打开权限弹窗的方法
const openPremission = (row) => {
  console.log(row);
  premissionModal.value = true;
  roleId.value = row._id;
  roleName.value = row.roleName;
  // 先把对象中的权限列表解构出来
  let { checkedKeys } = row.premissionList;
  // 使用setCheckKey去把id赋值到tree控件中，显示对应的权限
  setTimeout(() => {
    // 用setCheckKey是tree节点的方法
    // 获取节点mounted 确保节点一定获取了
    tree.value.setCheckKeys(checkedKeys);
  });
};
// 定义权限弹窗中的提交事件
const premissionSubmit = async () => {
  // 如何获取选中的checkedKeys =[]
  let nodes = tree.value.getCheckedNodes();
  console.log(nodes);
  // 如何获取选中的halfCheckedKeys =[]
  let halfChecked = tree.value.getHalfCheckedKeys();
  console.log(halfChecked);
  // 定义存放选中的节点
  let parentKeys = [];
  let checkedKeys = [];
  nodes.forEach(async (node) => {
    // 先判断选中的是按钮还是菜单
    if (!nodes.children) {
      // 说明是按钮
      checkedKeys.push(node._id);
    } else {
      // 说明是菜单
      parentKeys.push(node._id);
    }
    console.log(checkedKeys, parentKeys);
    let HalfCheckedKeys = parentKeys.concat(halfCheck);
    let data = {
      _id: roleId.value,
      premissionList: {
        checkedKeys,
        HalfCheckedKeys,
      },
    };
    // 发请求
    await api.updatePermission(data);
    // 关闭弹窗
    premissionModal.value = false;
    premissionSubmit();
  });
};
// 定义tree节点
const tree = ref(null);
// 定义菜单列表
const menuList = ref([]);
// 请求菜单列表
const getMenuList = async () => {
  let list = await api.getMenuList();
  menuList.value = list;
};
getMenuList();
// 定义菜单映射表
let actionMap = reactive({});
// 定义建立映射表的方法
const getActionMap = (list) => {
  // list是请求过来的数据
  let map = {};
  const deep = (arr) => {
    while (arr.length) {
      let item = arr.pop();
      // item就代表了每个对象 一级菜单
      if (item.children && item.action) {
        // 二级菜单
        map[item._id] = item.menuName;
      }
      if (item.children && !item.action) {
        // 一级菜单
        deep(item.children);
      }
    }
  };
  deep(JSON.parse(JSON.stringify(list)));
  console.log(map);
  actionMap = map;
};
getActionMap(storage.getItem("menuList"));
// 定义记录用户行为
const action = ref("add");
// 定义弹窗变量
const showMadol = ref(false);
// 定义获取表单节点dialogForm
const dialogForm = ref(null);
// 定义角色列表
let roleList = ref([]);
// 定义角色列表请求参数，也可以作为初始化的表单
let roleForm = reactive({});
// 获取角色列表
const getRoleAllList = async () => {
  let res = await api.getRoleAllList();
  roleList.value = res.list;
  console.log(roleList);
};
getRoleAllList();

// 定义动态表格--格式
const columns = reactive([
  {
    label: "角色名称",
    prop: "roleName",
  },
  {
    label: "备注",
    prop: "remark",
  },
  {
    label: "权限列表",
    prop: "permissionList",
    width: 200,
    formatter: (row, column, value) => {
      // 显示的数组
      let names = [];
      let halfKeys = value.HalfCheckedKeys || [];
      // 当前对象的权限Id
      // 去查找actionMap
      halfKeys.map((key) => {
        let name = actionMap[key];
        if (key && name) {
          names.push(name);
        }
      });
      return names.join(",");
    },
  },
  {
    label: "更新时间",
    prop: "updateTime",
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "创建时间",
    prop: "createTime",
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    },
  },
]);
// 重置表单事件
const resetForm = () => {
  dialogForm.value.resetFields();
};
// 定义创建用户按钮事件
const roleCreate = () => {
  action.value = "create";
  showMadol.value = !showMadol.value;
};
// 定义创建事件
const handleSubmit = () => {
  // console.log(roleForm);
  dialogForm.value.validate(async (vaild) => {
    if (vaild) {
      let data = toRaw(roleForm);
      console.log(roleForm);
      data.action = action.value;
      let res = await api.roleOperate(data);
      showMadol.value = !showMadol.value;
      resetForm();
      getRoleAllList();
    }
  });
};
// 定义查询事件
const onSubmit = async () => {
  let res = await api.getRoleAllList(roleForm);
  roleList.value = res.list;
};
// 定义编辑事件
const edit = (row) => {
  console.log(row);
  action.value = "edit";
  showMadol.value = !showMadol.value;
  nextTick(() => {
    Object.assign(roleForm, row);
  });
};
// 定义装数据的数组
let userListArr = {
  userIds: [],
};
// 定义删除事件
const del = async (row) => {
  action.value = "delete";
  let data = {
    _id: row._id,
    action: action.value,
    roleName: row.roleName,
    remark: row.remark,
  };
  console.log(data);
  await api.roleOperate(data);
  getRoleAllList();
};
</script>

<style lang="scss" scoped></style>
